<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="考试编号" prop="examCode">
        <el-input
          v-model="queryParams.examCode"
          placeholder="请输入考试编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="考试名称" prop="description">
        <el-input
          v-model="queryParams.description"
          placeholder="请输入考试名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程名称" prop="source">
        <el-input
          v-model="queryParams.source"
          placeholder="请输入课程名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['module:exam:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['module:exam:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['module:exam:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['module:exam:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="examList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="考试编号" align="center" prop="examCode" />
      <el-table-column label="考试名称" align="center" prop="description" />
      <el-table-column label="课程名称" align="center" prop="source" />
      <el-table-column label="试卷名称" align="center" prop="description" >
        <template #default="scope">
          <span >
                <router-link
      :to="`/exam/paper/index/${encodeURIComponent(scope.row.examCode)}`"
      class="link-type"
    >{{ scope.row.description+"试卷"}}
              </router-link>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="考试日期" align="center" prop="examDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.examDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- 这里需要点击发布请求 -->
      <el-table-column label="是否发布" align="center" key="isPublic" prop="isPublic" >
                <template #default="scope">
                  <el-switch
                    v-model="scope.row.isPublic"
                    :active-value="1"
                    :inactive-value="0"
                    @change="(value) => handleStatusChange(scope.row, value)"
                  ></el-switch>
                </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['module:exam:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['module:exam:remove']">删除</el-button>
          <router-link :to="`/exam/paper/index/${encodeURIComponent(scope.row.examCode)}`"
      class="link-type">
            <el-button link type="primary" icon="Edit" >编辑试卷</el-button>
          </router-link>
                    <router-link :to="`/exam/paper/detail/${encodeURIComponent(scope.row.examCode)}`"
      class="link-type">
            <el-button link type="primary" icon="Edit" >试卷预览</el-button>
          </router-link>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改考试管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="examRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="考试名称" prop="description">
          <el-input v-model="form.description" placeholder="请输入考试名称" />
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-select v-model="form.major" placeholder="请选择专业">
            <el-option
              v-for="dict in sys_major_name"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程名称" prop="source">
          <el-input v-model="form.source" placeholder="请输入课程名称" />
        </el-form-item>
        <el-form-item label="考生须知" prop="tips">
          <el-input v-model="form.tips" placeholder="请输入考生须知" />
        </el-form-item>
        <el-form-item label="考试日期" prop="examDate">
          <el-date-picker clearable
            v-model="form.examDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择考试日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="持续时长" prop="totalTime">
          <el-input v-model="form.totalTime" placeholder="请输入持续时长" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Exam">
import { listExam, getExam, delExam, addExam, updateExam,releaseExam } from "@/api/module/exam"
import { onMounted } from "vue";

const { proxy } = getCurrentInstance()
const { sys_major_name } = proxy.useDict('sys_major_name')

const examList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    examCode: null,
    description: null,
    source: null,
  },
  rules: {
    description: [
      { required: true, message: "考试名称不能为空", trigger: "blur" }
    ],
    major: [
      { required: true, message: "专业不能为空", trigger: "change" }
    ],
    source: [
      { required: true, message: "课程名称不能为空", trigger: "blur" }
    ],
    type: [
      { required: true, message: "考试类型不能为空", trigger: "change" }
    ],
    examDate: [
      { required: true, message: "考试日期不能为空", trigger: "blur" }
    ],
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询考试管理列表 */
function getList() {
  loading.value = true
  listExam(queryParams.value).then(response => {
    examList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    examCode: null,
    description: null,
    major: null,
    source: null,
    type: null,
    tips: null,
    paperId: null,
    paperDetail: null,
    paperProblemArray: null,
    examDate: null,
    totalTime: null,
    totalScore: null,
    isPublic: null
  }
  proxy.resetForm("examRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.examCode)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加考试管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _examCode = row.examCode || ids.value
  getExam(_examCode).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改考试管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["examRef"].validate(valid => {
    if (valid) {
      if (form.value.examCode != null) {
        updateExam(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addExam(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _examCodes = row.examCode || ids.value
  proxy.$modal.confirm('是否确认删除考试管理编号为"' + _examCodes + '"的数据项？').then(function() {
    return delExam(_examCodes)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('module/exam/export', {
    ...queryParams.value
  }, `exam_${new Date().getTime()}.xlsx`)
}
onMounted(()=>{
  getList()
})



function handleStatusChange(row, newStatus) {
  const originalStatus = row.isPublic;
  const action = newStatus == 1 ? "发布" : "隐藏";
  
  proxy.$modal.confirm(`确认要${action}吗?`).then(() => {
    return releaseExam({
      examCode: row.examCode,
      isPublic: newStatus
    })
  }).then(() => {
    proxy.$modal.msgSuccess(`${action}成功`)
  }).catch(() => {
    // 请求失败时恢复原始状态
    row.isPublic = originalStatus;
  })
}


</script>
